package com.dearbinge.opentapi.content.cart;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.dearbinge.data.api.cart.CartService;
import com.dearbinge.data.pojo.cart.Cart;
import com.dearbinge.data.pojo.cart.vo.CartVO;
import com.dearbinge.data.pojo.confirm.Do.ConfirmDo;
import com.dearbinge.data.redis.service.RedisService;
import com.dearbinge.utils.Constants;
import com.dearbinge.utils.ResultMsg;
import com.dearbinge.utils.enums.ResultStatusCodeEnum;

import io.swagger.annotations.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

/**
 * 购物车控制层
 *
 * @author cl
 * @date 2019/1/10
 */
@Api(description = "购物车")
@RestController
@RequestMapping("/cart")
@CrossOrigin
@EnableAutoConfiguration
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
	private RedisService redisService;
    /**
     * 增加修改购物车
     *
     * @param cart 购物车
     * @return 结果提示
     * @author cl
     * @date  2019/02/15
     */
    @ApiOperation(value = "增加修改购物车", notes = "增加修改购物车")
    @RequestMapping(value = "/insertOrUpdateCart", method = RequestMethod.POST)
    public ResultMsg<String> insertOrUpdateCart(@RequestBody Cart cart) {



        try {
            Integer dataCode ;

            String CommodityId = cart.getCommodityId();
            //获取指定商品库存
            Integer total = cartService.getCommodityStock(CommodityId);



            if(null == total){
                return ResultMsg.error(500,"商品不存在");
            }

            if(cart.getTotal() <=0){
                return ResultMsg.error(500,"数量必须大于1");
            }

            //校验商品库存
            if (total < cart.getTotal()){
                return ResultMsg.error(500,"商品库存不足");
            }

            if(null == cart.getCheck()){
                cart.setCheck(false);
            }

            if(cart.getChecked() == null){
                cart.setChecked(false);
            }

            if(cart.getCommoditySpecId() == null || cart.getCommoditySpecId().equals("")){
                cart.setCommoditySpecId(null);
            }

            //查询商品是否存在用户购物车
            CartVO cartVO = cartService.getCommodityInCart(cart);

            if(cartVO == null && cart.getId() == null || cartVO == null && cart.getId() ==0 ){
                //商品来源不能为空
                if(null == cart.getSource()){
                    return ResultMsg.error(500,"商品来源不能为空");
                }
                dataCode = cartService.insertCart(cart);
                if (dataCode >0){
                    return ResultMsg.ok("增加成功");
                }
            }else {
                Integer id = cart.getId();
                if(null != cartVO){
                    id = cartVO.getId();
                }
                cart.setId(id);
                dataCode = cartService.updateCart(cart);
                if (dataCode >0){
                    return ResultMsg.ok("修改成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除购物车", notes = "根据ID删除购物车")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query")
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public ResultMsg<String> delete(Integer id) {
        try {
            Integer dataCode = cartService.deleteCart(id);
            if (dataCode > 0){
                return ResultMsg.ok("删除成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    /**
     * 清空指定用户的失效商品购物车
     */
    @ApiOperation(value = "清空指定用户的失效商品购物车", notes = "清空指定用户的失效商品购物车")
    @ApiImplicitParam(name = "userId", value = "用户id", paramType = "query")
    @RequestMapping(value = "/deleteUserFailureCart",method = RequestMethod.GET)
    public ResultMsg<String> deleteUserFailureCart(String userId) {
        try {
            Integer dataCode = cartService.deleteUserFailureCart(userId);
            if (dataCode > 0){
                return ResultMsg.ok("删除成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    /**
     * 查询用户的购物车
     */
    @ApiOperation(value = "查询用户的购物车", notes = "查询用户的商品购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", paramType = "query", required = true),
            @ApiImplicitParam(name = "current", value = "当前页", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页面数量", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(response = CartVO.class, code = 200, message = "返回结果参数")
    })
    @RequestMapping(value = "/listCartByUserId", method = RequestMethod.GET)
    public ResultMsg<Page> listCartByUserId(String userId, Integer current, Integer size) {
        try {
            Page page = cartService.listCartByUserId(userId, current, size);
            return ResultMsg.okData(page, ResultStatusCodeEnum.SUCCESS.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }

    @ApiOperation(value = "确认订单", notes = "确认订单")
    @RequestMapping(value = "/getConfirm", method = RequestMethod.POST)
    public ConfirmDo getConfirm(@RequestBody ConfirmDo confirmDo) {
        return confirmDo;
    }

    @ApiOperation(value = "订单确认页面保存临时数据", notes = "订单确认页面保存临时数据")
    @ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户ID",paramType = "query"),
		@ApiImplicitParam(name = "content", value = "要保存的数据",paramType = "query"),
	})
    @RequestMapping(value = "/saveTemporaryData", method = RequestMethod.POST)
    public ResultMsg<String> saveTemporaryData(@RequestBody String jsonObject) {
    	 try {
    		JSONObject parseObject = JSON.parseObject(jsonObject);
    		String userId = (String) parseObject.get("userId");
    		Object object = parseObject.get("content");
    		redisService.set("saveTemporaryData"+":"+userId, object.toString());
    		redisService.expired("saveTemporaryData"+":"+userId,600);
         }catch (Exception e){
             e.printStackTrace();
             return ResultMsg.error(500,"系统异常");
         }
         return ResultMsg.ok("ok");
    }

    @ApiOperation(value = "订单确认页面获取临时数据", notes = "订单确认页面获取临时数据")
    @ApiImplicitParam(name = "userId", value = "用户ID",paramType = "query")
    @RequestMapping(value = "/getTemporaryData", method = RequestMethod.GET)
    public ResultMsg<com.alibaba.fastjson.JSONArray> getTemporaryData(String userId) {
    	com.alibaba.fastjson.JSONArray OrderTableDtoList;
    	try {
    		 OrderTableDtoList = JSON.parseArray(redisService.get("saveTemporaryData"+":"+userId));
         }catch (Exception e){
             e.printStackTrace();
             return ResultMsg.error(500,"系统异常");
         }
         return ResultMsg.ok(OrderTableDtoList);
    }
}
